/* eslint-disable @typescript-eslint/no-unused-vars */
import React from 'react';
import { Table, Button, Row, message } from 'antd';
import { useWorkFlow, useRequest } from '@/hooks';
import { getLeavingProveList } from '@/pages/TurnoverSetting/LeaveSetting/services';
import { Link, router } from 'umi';
import { TableFilter } from '@/components';
// import { Organization } from '@/containers';
import {
    renderShortDate,
    renderNameWithReadFlagTitle,
    // renderNameWithReadFlag,
    renderLeaveStatus,
    renderLeaveType,
    renderCustomText,
    renderDealPeople
} from '@/pages/OnboardAndLeave/LeaveManagement/renderUtil';
import GradeSelector from '@/pages/Organization/Job/components/GradeSelector';
import useDictionary from '@/hooks/useDictionary';
import { toArray } from '@/utils/utils';
import authHelper from '@/utils/auth/helper';
import { useGradeList } from '@/pages/Organization/Job/hooks';
// import { Switch } from 'dva/router';
import { TRIAL_STATUS_LABEL_LIST } from '@/pages/Informal/constants';
import { PrintModal } from '@/pages/WorkFlow/OnboardAndLeave/QuitManagement/QuitHandover/components/PrintModal';
import TalkDrawer from '@/pages/WorkFlow/components/CustomComponents/DimissionApply/containers/Talk/TalkDrawer';
import FilterOrganization from './FilterOrganization';
import { LEAVE_STATUS, LEAVE_TYPE, LEAVE_STATUS_OBJ, getOperate } from '../../dictionary';
import styles from '../index.less';
import OperateButton from './OperateButton';
import DesignateModal from './DesignateModal';
// import { getDisplayText } from '@/utils/dataDictUtil';
const { checkCode } = authHelper;

const getOperateBtns = ({
    record,
    view,
    setDrawerProps,
    employeeCode,
    setVisible,
    setDesignateProps,
    setDesignateVisible,
    setPrintModalVisible,
    setPrintDetailData,
    // setTemplateContent,
    // leaveTemplateObj,
    setPrintId
}) => {
    const {
        currentDealEmployeeCode, // 当前处理人数组
        assessEmployeeCodes,
        dimissionStatus,
        initiatorCode,
        interviewerReadyInfo,
        processInstanceId,
        currentDealLeaderCode,
        interviewerReadyEmployeeCodes,
        dimissionTemplateId,
        companyName,
        employeeName,
        idCard,
        dutyName,
        entryDate,
        finalDimissionDate
    } = record;

    const arrayBtns = [];
    const isCurrentDeal = currentDealEmployeeCode?.includes(employeeCode);
    const isLeader = currentDealLeaderCode?.includes(employeeCode);
    const isReadyInterview = interviewerReadyEmployeeCodes.length > 0;
    // const isReadyInterview = interviewerReadyEmployeeCodes?.includes(employeeCode);
    // 跳转到审批、审批详情页面
    const gotoApprovePage = () => {
        view({ processInstanceId });
    };
    // 发起、修改面谈
    const gotoInterview = () => {
        setDrawerProps({
            // initialData: lastData, // 设计的限制只能编辑/删除最新
            employeeCode: record.employeeCode,
            employeeName: record.employeeName,
            processInstanceId
            // callback: refresh
        });
        setVisible(true);
    };
    // 修改处理人
    const showDesignateModal = () => {
        setDesignateProps({
            currentDealEmployeeName: record.currentDealEmployeeName,
            employeeCode: record.currentDealEmployeeCode,
            id: record.id
        });
        setDesignateVisible(true);
    };
    // 打印离职证明
    const printCertificate = () => {
        setPrintDetailData({
            companyName,
            employeeName,
            idNumber: idCard,
            dutyName,
            entryDate,
            dimissionDate: finalDimissionDate
        });
        // setTemplateContent(leaveTemplateObj[dimissionTemplateId || 0]);
        setPrintId(dimissionTemplateId);
        setPrintModalVisible(true);
    };
    switch (dimissionStatus) {
        case LEAVE_STATUS_OBJ.PROCESSING:
            if (isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'approve', gotoApprovePage));
                arrayBtns.push(getOperate(record, 'initiateInterview', gotoInterview));
            } else {
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            }
            break;
        case LEAVE_STATUS_OBJ.WAITING_INTERVIEW:
            if (isCurrentDeal) {
                if (isReadyInterview) {
                    arrayBtns.push(getOperate(record, 'startInterview'));
                    arrayBtns.push(getOperate(record, 'modifyInterviewPreparation'));
                    arrayBtns.push(getOperate(record, 'editInterview', gotoInterview));
                } else {
                    arrayBtns.push(getOperate(record, 'preparingInterview'));
                    arrayBtns.push(getOperate(record, 'editInterview', gotoInterview));
                }
            } else {
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            }
            // // 评估人
            // if (assessEmployeeCodes.includes(employeeCode)) {
            //     // todo
            //     if (interviewerReadyInfo.includes(employeeCode)) {
            //         arrayBtns.push(getOperate(record,'modifyInterviewPreparation'));
            //         arrayBtns.push(getOperate(record,'startInterview'));
            //     } else {
            //         arrayBtns.push(getOperate(record,'preparingInterview'));
            //     }
            // } else if (initiatorCode === employeeCode) {
            //     // 发起人
            //     // eslint-disable-next-line no-lonely-if
            //     if (assessEmployeeCodes.includes(employeeCode)) {
            //         arrayBtns.push(getOperate(record,'modifyInterviewPreparation'));
            //         arrayBtns.push(getOperate(record,'startInterview'));
            //         arrayBtns.push(getOperate(record,'editInterview'));
            //     } else {
            //         arrayBtns.push(getOperate(record,'preparingInterview'));
            //         arrayBtns.push(getOperate(record,'editInterview'));
            //     }
            // }
            // arrayBtns.push(getOperate(record,'approveDetail'));
            break;
        case LEAVE_STATUS_OBJ.TO_SUMMARIZE:
            if (isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'interviewSummary'));
            } else {
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            }
            break;
        case LEAVE_STATUS_OBJ.WORK_HANDOVER:
            if (isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'workHandover'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            } else {
                arrayBtns.push(getOperate(record, 'handoverDetail'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            }
            if (isLeader || isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'modificationHandler', showDesignateModal)); // 修改处理人
            }
            break;
        case LEAVE_STATUS_OBJ.PERSONNEL_HANDOVER:
            if (isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'personnelHandover'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            } else {
                arrayBtns.push(getOperate(record, 'handoverDetail'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            }
            if (isLeader || isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'modificationHandler', showDesignateModal)); // 修改处理人
            }
            break;
        case LEAVE_STATUS_OBJ.IT_HANDOVER:
            if (isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'itHandover'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            } else {
                arrayBtns.push(getOperate(record, 'handoverDetail'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            }
            if (isLeader || isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'modificationHandler', showDesignateModal)); // 修改处理人
            }
            break;
        case LEAVE_STATUS_OBJ.ADMINISTRATIVE_HANDOVER:
            if (isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'administrativeHandover'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            } else {
                arrayBtns.push(getOperate(record, 'handoverDetail'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            }
            if (isLeader || isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'modificationHandler', showDesignateModal)); // 修改处理人
            }
            break;
        case LEAVE_STATUS_OBJ.FINANCIAL_SETTLEMENT:
            if (isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'financialHandover'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            } else {
                arrayBtns.push(getOperate(record, 'handoverDetail'));
                arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            }
            if (isLeader || isCurrentDeal) {
                arrayBtns.push(getOperate(record, 'modificationHandler', showDesignateModal)); // 修改处理人
            }
            break;
        case LEAVE_STATUS_OBJ.FINISH_HANDOVER:
            arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            arrayBtns.push(getOperate(record, 'handoverDetail'));
            // arrayBtns.push(getOperate(record, 'printCertificate', printCertificate));
            break;
        case LEAVE_STATUS_OBJ.HAVE_LEFT:
            arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            arrayBtns.push(getOperate(record, 'handoverDetail'));
            arrayBtns.push(getOperate(record, 'printCertificate', printCertificate));
            break;
        case LEAVE_STATUS_OBJ.ABORT_LEFT:
            arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            break;
        case LEAVE_STATUS_OBJ.WITHDRAW_APPLICATION:
            arrayBtns.push(getOperate(record, 'approveDetail', gotoApprovePage));
            break;
        default:
            break;
    }

    return (
        <Row type="flex" align="middle" className={styles.commonSplit}>
            {arrayBtns?.map((item, index) => (
                <OperateButton key={index} {...item} />
            ))}
        </Row>
    );
};

export default function LeaveTable({
    fetchList,
    dataSource,
    handleTableChange,
    loading,
    condition,
    sortOrders,
    type,
    location,
    ...rest
}) {
    const { query } = location.location;
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const { employeeCode } = user;
    const [visible, setVisible] = React.useState(false);
    const [designateVisible, setDesignateVisible] = React.useState(false);
    const [drawerProps, setDrawerProps] = React.useState({
        // initialData: lastData, // 设计的限制只能编辑/删除最新
        employeeCode: '',
        employeeName: '',
        processInstanceId: ''
        // callback: refresh
    });
    const [designateProps, setDesignateProps] = React.useState({
        currentDealEmployeeName: '',
        employeeCode: ''
    });
    const [printModalVisible, setPrintModalVisible] = React.useState(false);
    const [printDetailData, setPrintDetailData] = React.useState();
    // const [templateContent, setTemplateContent] = React.useState('');
    const [leaveTemplateObj, setLeaveTemplateObj] = React.useState({});
    const [printId, setPrintId] = React.useState();
    // 获取离职模版列表
    const { data: printTemplatelist } = useRequest(getLeavingProveList, {
        formatResult: res => {
            if (res) {
                const { code, data: templatelist, msg } = res;
                if (code === 10000) {
                    const obj = {};
                    for (let i = 0, len = templatelist.length; i < len; i += 1) {
                        obj[templatelist[i].id] = templatelist[i].templateContent;
                    }
                    setLeaveTemplateObj(obj);
                    return templatelist;
                }
                message.error(msg);
            }
            return undefined;
        }
    });
    const getColumnSearchProps = dataIndex => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <FilterOrganization
                placeholder="请选择组织机构"
                getPopupContainer={triggerNode => triggerNode.parentElement}
                treeDefaultExpandAll
                showSearch={false}
                value={selectedKeys}
                onChange={e => {
                    setSelectedKeys(e || []);
                    confirm();
                }}
            />
        ),
        render: (text, record) => <span>{record?.organizationName}</span>

        // filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />,
    });
    const { view } = useWorkFlow({ launchParam: { type: 'TransferPositionApply' } });

    // const getHistoryOperateBtns = record => {
    //     const arrayBtns = [];
    //     arrayBtns.push(getOperate(record)('approveDetail'));
    //     arrayBtns.push(getOperate(record)('handoverDetail'));
    //     return (
    //         <Row type="flex" align="middle" className={styles.commonSplit}>
    //             {arrayBtns?.map((item, index) => (
    //                 <OperateButton key={index} {...item} />
    //             ))}
    //         </Row>
    //     );
    // };
    let arr = [];
    if (type !== 2) {
        arr = [
            {
                title: '处理人',
                dataIndex: 'currentDealEmployeeName',
                key: 'currentDealEmployeeName',
                render: val => renderDealPeople(val)
            }
        ];
    }
    const columns = React.useMemo(
        () => [
            {
                title: renderNameWithReadFlagTitle('姓名'),
                dataIndex: 'employeeName',
                key: 'employeeName'
                // render: (text, record) => (
                //     <>
                //         {checkCode('office:personnel:progress:entry:detail') ? (
                //             <Link
                //                 to={{
                //                     pathname: '/office/personnelManagement/organization/employeeList/detail',
                //                     query: { employeeCode: record.employeeCode }
                //                 }}
                //             >
                //                 {text}
                //             </Link>
                //         ) : (
                //             text
                //         )}
                //     </>
                // )
                // dataIndex: 'readFlag',
                // render: (value, record) => {
                //     const { employeeName = '--', showReadFlag, hasBlackList } = record;
                //     return renderNameWithReadFlag(employeeName, value, showReadFlag, hasBlackList);
                // }
            },
            {
                title: '组织机构',
                dataIndex: 'organizationName',
                key: 'organizationName',
                render: (text, record) => renderCustomText(text, record?.fullPathOrganizationName)
                // ...getColumnSearchProps('organizationCode')
                // filteredValue: condition?.organizationCode ? [condition?.organizationCode] : [],

                // filters: filterArray?.filter(item => item.key === 'organizationCode'),
                // filterMultiple: false,
                // filterDropdown: filterProps => <TableFilter {...filterProps} />
            },
            { title: '行政机构', dataIndex: 'companyName', key: 'companyName' },
            { title: '岗位', dataIndex: 'dutyName', key: 'dutyName' },
            {
                title: '职级',
                dataIndex: 'rankValue',
                key: 'rankValue'
            },
            {
                title: '申请日期',
                width: 150,
                dataIndex: 'applyTime',
                key: 'apply_time', // 排序用到
                sorter: sortOrders?.applyTime || true,
                render: val => renderShortDate(val, 'YYYY-MM-DD')
            },
            {
                title: '离职类型',
                dataIndex: 'dimissionType',
                key: 'dimissionType',
                render: (val, record) => {
                    if (val === 2) {
                        return renderLeaveType(val, `由 ${record?.applyEmployeeName} 发起的`);
                    }
                    return renderLeaveType(val, '');
                }
            },
            {
                title: '离职日期',
                width: 150,
                dataIndex: 'finalDimissionDate',
                key: 'final_dimission_date', // 排序用到
                sorter: sortOrders?.finalDimissionDate || true,
                render: val => renderShortDate(val, 'YYYY-MM-DD')
            },
            {
                title: '状态',
                dataIndex: 'dimissionStatus',
                key: 'dimissionStatus',
                filters: LEAVE_STATUS.filter(s => s.type === type),
                filteredValue: query?.dimissionStatus && query?.dimissionStatus.split(','),
                // filteredValue: query?.dimissionStatus,
                render: (val, record) => renderLeaveStatus(val, record)
            },
            ...arr,
            {
                title: '操作',
                dataIndex: 'work',
                key: 'work',
                fixed: 'right',
                align: 'left',
                width: 200,
                onCell: () => ({
                    onClick: e => {
                        e.stopPropagation();
                    }
                }),
                // render: (_, record) => {
                //     if (type === 1) {
                //         return getOperateBtns({ record, view, setDrawerProps, employeeCode, setVisible });
                //     }
                //     return getHistoryOperateBtns(record);
                // }
                render: (_, record) =>
                    getOperateBtns({
                        record,
                        view,
                        setDrawerProps,
                        employeeCode,
                        setVisible,
                        setDesignateProps,
                        setDesignateVisible,
                        printModalVisible,
                        setPrintModalVisible,
                        setPrintDetailData,
                        // setTemplateContent,
                        // leaveTemplateObj,
                        setPrintId
                    })
            }
        ],
        []
    );
    return (
        <div style={{ marginTop: 24, marginBottom: 10 }}>
            <Table
                columns={columns}
                rowClassName={styles.tableRow}
                dataSource={dataSource}
                onChange={handleTableChange}
                loading={loading}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onRow={record => ({
                    onClick: () => {
                        history.push({
                            pathname: '/office/personnelManagement/organization/employeeList/detail',
                            query: { employeeCode: record.employeeCode }
                        });
                    }
                })}
            />
            {visible && <TalkDrawer {...drawerProps} setVisible={setVisible} visible={visible} callback={fetchList} />}
            {designateVisible && (
                <DesignateModal
                    fetchList={fetchList}
                    setDesignateVisible={setDesignateVisible}
                    designateVisible={designateVisible}
                    {...designateProps}
                />
            )}
            {printModalVisible && (
                <PrintModal
                    visible={printModalVisible}
                    detailData={printDetailData}
                    templateContent={leaveTemplateObj[printId] || printTemplatelist[0].templateContent}
                    handleCancel={() => {
                        setPrintModalVisible(false);
                    }}
                />
            )}
        </div>
    );
}
